<template>
  <div class="cus-table">
    <Table ref="tDom" :border="border" :stripe="stripe" :size="size" :loading="loading" :columns="columns" :data="data"
      :width="width" :height="tableHeight" :row-class-name="rowClassName" :span-method="handleSpan"
      :highlight-row="highlightRow" @on-current-change="onCurrentChange"
      @on-cell-click="onCellClick" @on-row-click="onRowClick" @on-select-all="onSelectAll"
      @on-selection-change="onSelectionChange" @on-select-cancel="onSelectCancel"
      @on-select-all-cancel="onSelectAllCancel">
      <!-- <tableSlot :columns = columns></tableSlot> -->
      <template v-for="column in slotList" slot-scope="{ row, index }" :slot="column.slot">
        <slot :name="column.slot" :row="row" :index="index" v-if="column.slot"> </slot>
      </template>
    </Table>
  </div>
</template>

<script>
/**
 * @columns Table表头
 * @data    Table表格数据
 * @loading 表格懒加载
 * @width   表格宽度，单位 px
 * @height  表格高度
 * @border  是否显示纵向边框
 * @stripe  是否显示间隔斑马纹
 * @size    表格尺寸，可选值为 large、small、default 或者不填
 */
import tableSlot from "./tableSlot/tableSlot.vue";
export default {
  name: "cus-table",
  data() {
    return {
      tableHeight: 0,
      customHeight: 0,
      observer: null,
    };
  },
  components: { tableSlot },
  props: {
    columns: {
      type: Array,
      default: () => [],
    },
    data: {
      type: Array,
      default: () => [],
    },
    width: {
      type: [String, Number],
      default: 0,
    },
    highlightRow: {
      type: Boolean,
      default: false,
    }, 
    height: {
      type: [String, Number],
      default: "",
    },

    size: {
      type: [String, Number],
      default: "default",
    },
    border: {
      type: Boolean,
      default: false,
    },
    stripe: {
      type: Boolean,
      default: false,
    },
    index: {
      type: Number,
      default: 0
    },
    loading: {
      type: Boolean,
      default: false,
    },
    handleSpan: {
      type: Function,
    },
    rowClassName: {
      type: Function,
    },
    bottomClass: {
      type: Array,
      default: () => [],
    },
  },

  computed: {
    // 通过递归
    slotList() {
      let slotList = [];
      let fun = (list) => {
        list.forEach((item) => {
          if (item.slot) {
            slotList.push(item);
          }
          if (item.children) {
            fun(item.children);
          }
        });
      };
      fun(this.columns);
      return slotList;
    },
  },

  mounted() {
    let that = this
    this.$nextTick(() => {
      // console.log(document.getElementsByClassName("cus-table")[0].getBoundingClientRect().top);
      this.getHeight();
    });
    this.observer = new MutationObserver(function (mutations) {
      // console.log('触发触发-------------------');
      // console.log('页面布局已经发生改变',that.customHeight);  
      that.getHeight();
      // 如果有任何 DOM 节点被修改则会调用这里的回调函数
      // console.log('页面布局已经发生改变',that.customHeight);  
    });

    // 配置观察选项
    var config = { attributes: false, childList: true, subtree: true };
    // 开始观察目标节点（此处为 document）及其所有后代节点
    this.observer.observe(document, config);
    // create an Observer instance
    // console.log("判断高度", document.body.clientHeight, document.body.scrollHeight);
    window.addEventListener("resize", this.tableHeightChange, true);
  },
  methods: {
    //	单击某个单元格触发
    onCellClick(row, column, data, event) {
      this.$emit("on-cell-click", { row, column, data, event });
    },
    // 第一次进入页面获取高度
    getHeight() {
      // debugger
      // console.log('--------------------------------------------22222');
      const table = document.getElementsByClassName("cus-table");
      // 没获取到return出去
      console.log('table', table);
      if (table.length == 0) return
      // console.log('table高度',table[0].offsetTop);
      // height为table到视图顶部的距离
      // 如果一页中有多个table，需要根据index去获取是哪个table
      const height = table[this.index].getBoundingClientRect().top;
  
      // 需要在下面留40px的边距
      this.customHeight = height + 40;
      // table在离下方又多少个盒子，遍历出他们的高度将其相加
      console.log('height', height);
      if (this.bottomClass.length > 0) {
        this.bottomClass.forEach((item) => {
          let itemDom = document.getElementsByClassName(`${item}`)[0];
          let maginTop = 0
          let marginBottom = 0
          // 有时候会丢失dom引发报错
          if (itemDom) {
            // 获取元素高度
            this.customHeight += itemDom.getBoundingClientRect().height;
            // 获取上下外边距
            maginTop = getComputedStyle(itemDom, null).marginTop;
            marginBottom = getComputedStyle(itemDom, null).marginBottom;
          }
          this.customHeight +=
            Number(maginTop ? maginTop.slice(0, -2) : 0) +
            Number(marginBottom ? marginBottom.slice(0, -2) : 0);
        });
      }
      // 得到最后需要减去的高度
      this.tableHeightChange();
    },
    // 获取table盒子
    getBottomHeight() { },
    // 单击某一行时触发
    onRowClick(e) {
      console.log(e,111);
      
      this.$emit("on-row-click", e);
    },
    // 开启 highlight-row 后有效，当表格的当前行发生变化的时候会触发
    onCurrentChange(e) {
      this.$emit("onCurrentChange", e);
    },
    // 在多选模式下有效，只要选中项发生变化时就会触发
    onSelectionChange(e) {
      console.log(123);
      this.$emit("on-selection-change", e);
    },
    // 在多选模式下有效，点击全选时触发
    onSelectAll(e) {
      this.$emit("on-select-all", e);
    },
    // 在多选模式下有效，取消选中某一项时触发
    onSelectCancel(e,row) {
      this.$emit("on-select-cancel", e,row);
    },
    // 在多选模式下有效，点击取消全选时触发
    onSelectAllCancel(e) {
      // log('12323')
      // this.$refs.tDom.selectAll()
      this.$emit("on-select-all-cancel", e);
    },
    // 操作dom
    tableDom(status) {
      this.$refs.tDom.selectAll(status);
    },
    // 设置Table表头高度自适应
    tableHeightChange() {
  
      // table在离下方又多少个盒子，遍历出他们的高度将其相加
      if (this.height) {
        this.tableHeight = this.height;
      } else if (this.customHeight) {
        this.tableHeight = window.innerHeight - this.customHeight; // 表格自适应高度
      }
    },
  },
  beforeDestroy() {
    // console.log('-----------------------------------------------------------',123);
    window.removeEventListener("resize", this.resizeHandle, true);
    this.observer.disconnect();
  },
};
</script>

<style lang="less"></style>
